package com.vislardo.app.notebook.utils;

import cn.hutool.core.util.StrUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

import java.nio.file.StandardOpenOption;
import java.util.Properties;

/**
 *
 * 管理
 * @author vislardo
 * @version 1.0
 * @since 2025-02-10
 */
public final class AppConfigManager {

    // 单例实例
    private static volatile AppConfigManager instance;

    // 配置存储对象（使用 Properties 或自定义数据结构）
    private Properties configs;

    //默认日记文件路径
    private static final String DEFAULT_FOLDER_DIR = "notefile";
    //默认临时文件路径
    private static final String DEFAULT_TEMP_FOLDER_DIR = "temp";


    private static final String PROPERTIES_FILE = "default.properties";
    private static final String DEFAULT_DATA_FOLDER = "data";

    private String resourcePath ;

    private String properties_file ;
    // 私有构造方法，防止外部实例化
    private AppConfigManager() {
         // 初始化时加载配置
    }

    // 全局访问点（双重检查锁定实现线程安全）
    public static AppConfigManager getInstance() {
        if (instance == null) {
            synchronized (AppConfigManager.class) {
                if (instance == null) {
                    instance = new AppConfigManager();
                    instance.loadConfig();
                }
            }
        }
        return instance;
    }

    public void loadConfig() {
        boolean auto_set_resource_path = false;
        configs = new Properties();
        this.resourcePath = System.getenv("VN_RESOURCE_PATH");

        if(StrUtil.isBlank(this.resourcePath)){
            auto_set_resource_path = true;
            this.resourcePath = AppConfigManager.class.getResource("/").getPath().substring(1);
            System.out.println("使用默认资源路径："+this.resourcePath);
        }

        Path properties = Path.of(this.resourcePath,PROPERTIES_FILE);

        if(Files.exists(properties)){
            configs = loadProperties(properties);
        }else{
            configs.setProperty("note.folder.path",this.getNoteFolderPath());
            configs.setProperty("temp.folder.path",this.getTempFolderPath());
            configs.setProperty("data.folder.path",this.getDataFolderPath());
            try(OutputStream os = Files.newOutputStream(Path.of(resourcePath,PROPERTIES_FILE))){
                configs.store(os,"自动创建");
            } catch (IOException e) {
                System.out.println("自动创建配置文件出现IO错误");
            }
        }

    }

    private Properties loadProperties(Path path){
        Properties properties = new Properties();
        try (InputStream input = Files.newInputStream(path, StandardOpenOption.READ)) {
            // 加载配置文件
            properties.load(input);
        } catch (IOException e) {
            throw new RuntimeException("Failed to load configuration file", e);
        }
        return properties;
    }

    public String getNoteFolderPath(){
        try{
            return getTargetFolderPath("note.folder.path",DEFAULT_FOLDER_DIR);
        }catch(IOException e){
            System.out.println("日记文件路径获取失败");
            e.printStackTrace();
        }
        return "";
    }

    public String getTempFolderPath(){
        try{
            return getTargetFolderPath("temp.folder.path",DEFAULT_TEMP_FOLDER_DIR);
        }catch(IOException e){
            System.out.println("临时文件路径获取失败");
            e.printStackTrace();
        }
        return "";
    }

    public String getDataFolderPath(){
        try{
            return getTargetFolderPath("data.folder.path",DEFAULT_DATA_FOLDER);
        }catch(IOException e){
            System.out.println("数据文件路径获取失败");
            e.printStackTrace();
        }
        return "";
    }


    private String getTargetFolderPath(String propKey,String defaultFolder) throws IOException{
        Path targetPath = null;
        String target_path = configs.getProperty(propKey);
        if(StrUtil.isBlank(target_path)){
            targetPath = Path.of(this.resourcePath,defaultFolder);
        }else{
            targetPath = Path.of(target_path);
        }
        Files.createDirectories(targetPath);

        return targetPath.toAbsolutePath().toString();

    }

}
